package cc.mcggdd.leah.boot.stock.controller;

import cc.mcggdd.leah.boot.stock.model.entity.StockHolding;
import cc.mcggdd.leah.boot.stock.model.form.StockHoldingForm;
import cc.mcggdd.leah.boot.stock.service.StockHoldingService;
import cc.mcggdd.leah.boot.stock.service.StockTradingService;
import cc.mcggdd.leah.boot.stock.service.impl.StockBillServiceImpl;
import cc.mcggdd.leah.boot.stock.service.impl.StockHoldingServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cc.mcggdd.leah.boot.stock.model.form.StockTradingForm;
import cc.mcggdd.leah.boot.stock.model.query.StockTradingQuery;
import cc.mcggdd.leah.boot.stock.model.vo.StockTradingVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cc.mcggdd.leah.boot.common.result.PageResult;
import cc.mcggdd.leah.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

/**
 * 交易明细前端控制层
 *
 * @author 
 * @since 2025-02-13 10:16
 */
@Tag(name = "交易明细接口")
@RestController
@RequestMapping("/api/v1/stockTradings")
@RequiredArgsConstructor
public class StockTradingController  {

    private final StockTradingService stockTradingService;
    private final StockHoldingService stockHoldingService;

    @Operation(summary = "交易明细分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('stock:stockTrading:query')")
    public PageResult<StockTradingVO> getStockTradingPage(StockTradingQuery queryParams ) {
        IPage<StockTradingVO> result = stockTradingService.getStockTradingPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "新增交易明细")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('stock:stockTrading:add')")
    public Result<Void> saveStockTrading(@RequestBody @Valid StockTradingForm formData ) {
        boolean result = false;
        String stockCode = formData.getCode();
        BigDecimal price = formData.getPrice();
        Integer number = formData.getNumber();
        BigDecimal amount = price.multiply(BigDecimal.valueOf(number)).abs();
        BigDecimal stampTax = (number > 0) ? BigDecimal.ZERO : amount.multiply(BigDecimal.valueOf(0.0005));
        BigDecimal commission = amount.multiply(BigDecimal.valueOf(0.0001)).compareTo(BigDecimal.valueOf(5)) == 1
                ? amount.multiply(BigDecimal.valueOf(0.0001)) : BigDecimal.valueOf(5);
        BigDecimal transfer = BigDecimal.ZERO;
        if (stockCode.startsWith("60") || stockCode.startsWith("900")) {
            transfer = amount.multiply(BigDecimal.valueOf(0.00001));
        }
        BigDecimal fee = stampTax.add(commission).add(transfer);

        formData.setAmount(amount);
        formData.setCommission(commission);
        formData.setStampTax(stampTax);
        formData.setFee(fee);
        if(formData.getHoldingId() == null || formData.getHoldingId() == 0){
            if(number < 0){
                return Result.failed("还没建仓呢，不能上来就卖吖");
            }
            
            StockHoldingForm stockHoldingForm = new StockHoldingForm();
            stockHoldingForm.setCode(stockCode);
            stockHoldingForm.setName(formData.getName());
            stockHoldingForm.setStartDate(formData.getDate());
            stockHoldingForm.setStatus("N");
            Long holdingId = stockHoldingService.saveStockHolding(stockHoldingForm);
            formData.setHoldingId(holdingId);
        }else{
            if(number < 0){
                Long holding = stockTradingService.getCountByHoldingId(formData.getHoldingId());
                if (holding.compareTo((long) Math.abs(number)) < 0) {
                    return Result.failed("持仓量不足");
                }
                if (holding.compareTo((long) Math.abs(number)) == 0) {
                    List<StockTradingVO> stockTradingVOList = stockTradingService.selectStockTradingListByHoldingId(formData.getHoldingId());
                    BigDecimal totalBuy = BigDecimal.ZERO;
                    BigDecimal totalSell = BigDecimal.ZERO;
                    for (StockTradingVO stockTrading : stockTradingVOList) {
                        if(stockTrading.getNumber().compareTo(0) > 0){
                            totalBuy = totalBuy.add(stockTrading.getAmount()).add(stockTrading.getFee());
                        }else{
                            totalSell = totalSell.add(stockTrading.getAmount());
                            // totalBuy = totalBuy.add(stockTrading.getFee());
                        }
                    }
                    // 还要加上本次记录
                    totalSell = totalSell.add(formData.getAmount());
                    // totalBuy = totalBuy.add(formData.getFee());
                    
                    StockHoldingForm stockHoldingForm = new StockHoldingForm();
                    stockHoldingForm.setId(formData.getHoldingId());
                    stockHoldingForm.setIncome(totalSell.subtract(totalBuy));
                    stockHoldingForm.setYield(totalSell.subtract(totalBuy).divide(totalBuy, 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                    stockHoldingForm.setEndDate(formData.getDate());
                    stockHoldingForm.setStatus("Y");
                    stockHoldingService.updateStockHolding(formData.getHoldingId(), stockHoldingForm);
                }
            }
        }

        result = stockTradingService.saveStockTrading(formData);

        return Result.judge(result);
    }

    @Operation(summary = "获取交易明细表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('stock:stockTrading:edit')")
    public Result<StockTradingForm> getStockTradingForm(
        @Parameter(description = "交易明细ID") @PathVariable Long id
    ) {
        StockTradingForm formData = stockTradingService.getStockTradingFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改交易明细")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('stock:stockTrading:edit')")
    public Result<Void> updateStockTrading(
            @Parameter(description = "交易明细ID") @PathVariable Long id,
            @RequestBody @Validated StockTradingForm formData
    ) {
        boolean result = stockTradingService.updateStockTrading(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除交易明细")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('stock:stockTrading:delete')")
    public Result<Void> deleteStockTradings(
        @Parameter(description = "交易明细ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = stockTradingService.deleteStockTradings(ids);
        return Result.judge(result);
    }
}
